package net.tensor.skynet.api.service.user

import net.tensor.skynet.api.base.PageResult
import net.tensor.skynet.api.base.QueryPage
import net.tensor.skynet.common.user.entity.User
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.mongodb.core.MongoTemplate
import org.springframework.data.mongodb.core.findAll
import org.springframework.data.mongodb.core.query.Criteria
import org.springframework.data.mongodb.core.query.Query
import org.springframework.data.mongodb.core.query.Update
import org.springframework.stereotype.Service
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable


@Service
class UserServiceImpl:UserService {
    @Autowired
    private lateinit var mongoTemplate: MongoTemplate

    @Autowired
    private lateinit var queryPage: QueryPage<User>

    override fun queryList(collectionName:String): List<User> {
        return mongoTemplate.findAll(collectionName)
    }

    override fun queryListGet(collectionName:String): List<User> {
        return mongoTemplate.findAll(collectionName)
    }

    override fun addOne(user: User): Any {
        return mongoTemplate.save(user)
    }

    override fun saveUser(user: User?) {
        user?.let { mongoTemplate.save(it) }
    }

    override fun removeUser(id: Int?) {
        val query = Query(Criteria.where("_id").`is`(id))
        mongoTemplate.remove(query, User::class.java)
    }

    override fun updateUser(user: User?) {
        val query = Query(Criteria.where("_id").`is`(user?.id))
        val update = Update()
        update["name"] = user?.name
        update["sex"] = user?.sex
        update["age"] = user?.age
        update["age"] = user?.code
        update["gradeId"] = user?.email
        mongoTemplate.updateFirst(query, update, User::class.java)
    }

    override fun findUserById(id: Long?): User? {
        val query = Query(Criteria.where("_id").`is`(id))
        return mongoTemplate.findOne(query, User::class.java)
    }

    override fun queryPage(pageSize: Int, pageNum: Int, query: Query): PageResult<User> {
        return queryPage.pagination(User::class.java,pageSize,pageNum, query)
    }
}